/**
 * Created by yufangjun on 16/4/16.
 */
function Orientation(selector) {

}

Orientation.prototype.init = function (option) {
    var self = this;
    this.dom = option.dom || document.body;
    this.width = option.width || 100;
    this.angle = option.angle || 90;
    var handler = function (evt) {
        self.orientationListener(evt, self);
    };
    window.removeEventListener('deviceorientation', handler);
    window.removeEventListener('devicemotion', handler);
    window.addEventListener('deviceorientation', handler, false);
    window.addEventListener('devicemotion', handler, false);
};

Orientation.prototype.orientationListener = function (evt, self) {
    // For FF3.6+
//        if (!evt.gamma && !evt.beta) {
//            // angle=radian*180.0/PI 在firefox中x和y是弧度值,
//            evt.gamma = (evt.x * (180 / Math.PI)); //转换成角度值,
//            evt.beta = (evt.y * (180 / Math.PI)); //转换成角度值
//            evt.alpha = (evt.z * (180 / Math.PI)); //转换成角度值
//        }
    /* beta:  -180..180 (rotation around x axis) */
    /* gamma:  -90..90  (rotation around y axis) */
    /* alpha:    0..360 (rotation around z axis) (-180..180) */

    var gamma = evt.gamma;
    var beta = evt.beta;
    var alpha = evt.alpha;
    var width = self.width;
    var dom = self.dom;
    var angle = self.angle;
    var minX = -width * 2 / 3;
    var maxX = 0;

//        3.14 * 670 / 180

    if (evt.accelerationIncludingGravity) {
        // window.removeEventListener('deviceorientation', this.orientationListener, false);
        gamma = event.accelerationIncludingGravity.x * 10;
        beta = -event.accelerationIncludingGravity.y * 10;
        alpha = event.accelerationIncludingGravity.z * 10;
    }
    if (gamma > angle / 2) {
        gamma = angle / 2;
    }
    if (gamma < -angle / 2) {
        gamma = -angle / 2;
    }

    if (this._lastGamma != gamma || this._lastBeta != beta) {

        var style = dom.style;
        var theX = gamma * 10 - width / 3;
//            document.querySelector("#J-gamma").innerHTML = "gamma: " + gamma;
//            document.querySelector("#J-num").innerHTML = "x: " + theX;
        if (theX > maxX) {
            theX = maxX;
        }
        if (theX < minX) {
            theX = minX;
        }
        style.backgroundPositionX = theX + "px";

        this._lastGamma = gamma;
        this._lastBeta = beta;
    }
};